content string |
|---|
"""
Find the k-th min of a binary search tree.
Bonus: find the k-th max.
"""
import unittest
class BST(object):
def __init__(self, value):
self.value = value
self.left, self.right = None, None
def build_bst():
_4 = BST(4)
_8 = BST(8)
_10 = BST(10)
_12 = BST(12)
_14 = BST(14)... |
import mmcv
def wider_face_classes():
return ['face']
def voc_classes():
return [
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat',
'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person',
'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'
]
... |
# -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp.osv import fields
import logging
_logger = logging.getLogger(__name__)
try:
import git
except ImportError:
_logger.warning("Please install GitPython==0.3.2")
import os
def get_diff_html(base_commit, main_commit=False):
if not main_commit:... |
from contextlib2 import ExitStack
from copy import copy
from logbook import Logger, Processor
from pandas.tslib import normalize_date
from zipline.finance.order import ORDER_STATUS
from zipline.protocol import BarData
from zipline.utils.api_support import ZiplineAPI
from six import viewkeys
from zipline.gens.sim_engin... |
"""FreeBSD platform implementation."""
import errno
import os
import _psutil_bsd
import _psutil_posix
import _psposix
from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
from psutil._compat import namedtuple
from psutil._common import *
__extra__all__ = []
# --- constants
NUM_CPUS = _psutil_bsd.ge... |
#!/usr/bin/env python3
# pylint: disable=C0111
import os
import gzip
import pandas as pd
from pyndl import io
TEST_ROOT = os.path.join(os.path.pardir, os.path.dirname(__file__))
FILE_PATH_SIMPLE = os.path.join(TEST_ROOT, "resources/event_file_simple.tab.gz")
TMP_SAVE_PATH = os.path.join(TEST_ROOT, "temp/event_file... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from collections import OrderedDict
from contextlib import contextmanager
from twitter.common.collections.orderedset import OrderedSet
from pants.backend.j... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ==================
# March 24, 2017
# ==================
ALL_ARTICLES_IDS_SAMPLE = """
prefix sg: <http://www.springernature.com/scigraph/ontologies/core/>
select ?a where {?a a sg:Article . ?a sg:scigraphId ?id} order by ?id limit 10
"""
ALL_ARTICLES_ID... |
#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
===============================================================================
Initialize System Configurations
===============================================================================
author=hal112358
-----------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
from gui_lib.textline import Textline
from verenigingSuggestion import findVerenigingSuggestion
import gui_lib.core as core
import curses
class VerenigingLine (Textline):
def __init__(self, width, attribute=curses.A_NORMAL, attribute_suggestion=curses.A_REVERSE):
super(VerenigingLine,self).__init__(width, "", attri... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import yaml
from collections import MutableMapping, MutableSet, MutableSequence
from ansible.compat.six import string_types
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.plugins import fragment_loa... |
from app.models import Customer
from app.views.base_view import BaseView
from app.modules.example_data import ExampleCustomers
from app.serializers import CustomerSerializer, CustomerDeserializer
from app.views.common import api_func
class CustomerListView(BaseView):
_model = Customer
_serializer = CustomerSe... |
'''Geometric symmetries
The symmetry tools in HORTON are just meant to provide optional additional
information on top of a System instance.
'''
import numpy as np
from horton.cext import Cell
from horton.exceptions import SymmetryError
from horton.periodic import periodic
__all__ = ['Symmetry']
class Symm... |
"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py
"""
from __future__ import division, absolute_import, print_function
__all__ = ['iscomplexobj', 'isrealobj', 'imag', 'iscomplex',
'isreal', 'nan_to_num', 'real', 'real_if_close',
'typename', 'asfarray', 'mintypecode', 'asscalar',
... |
"""event_manager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... |
"""
Interactive interpreter for interacting with Tor directly. This adds usability
features such as tab completion, history, and IRC-style functions (like /help).
"""
import os
import sys
import stem
import stem.connection
import stem.prereq
import stem.process
import stem.util.conf
import stem.util.system
import ste... |
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
Database abstraction layer for Sqlite and MySql
Copyright (C) 2012 Xycl
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,... |
import pexpect # type: ignore[import]
import pytest
from conftest import PS1, TestUnitBase, assert_bash_exec
@pytest.mark.bashcomp(
cmd=None, ignore_env=r"^[+-](COMP_(WORDS|CWORD|LINE|POINT)|_scp_path_esc)="
)
class TestUnitGetCword(TestUnitBase):
def _test(self, *args, **kwargs):
return self._test_... |
from django.db import models
from django.test import TestCase
from .api import register_index
from .lookups import StandardLookup
from .resolver import resolver
from djangotoolbox.fields import ListField
from datetime import datetime
import re
class ForeignIndexed2(models.Model):
name_fi2 = models.CharField(max_l... |
""" WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... |
"""
Base classes for writing management commands (named commands which can
be executed through ``django-admin.py`` or ``manage.py``).
"""
import os
import sys
from optparse import make_option, OptionParser
import django
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import ... |
"""Utility module to handle the virtwho configure UI/CLI/API testing"""
import re
import json
import uuid
from robottelo import ssh
from robottelo.config import settings
from robottelo.constants import DEFAULT_ORG
from robottelo.cli.host import Host
from robottelo.cli.virt_who_config import VirtWhoConfig
VIRTWHO_SYSCO... |
import webapp2
import os
import datetime
import json
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
class Msg(db.Model):
user = db.UserProperty(auto_current_user_add=True)
time = db.DateTimeProperty(auto_now_add=True)
message = db.StringPr... |
#!/usr/bin/env python2
import wx
from util import AddLinearSpacer
class LabeledWidget(wx.Panel):
def __init__(self, parent, cls, label, space=5, *args, **kwargs):
wx.Panel.__init__(self, parent)
self.widget = cls(parent=self, *args, **kwargs)
self.label = wx.StaticText(parent=self... |
import pymysql
from contextlib import contextmanager
from sqlalchemy import event, create_engine
from sqlalchemy.exc import DisconnectionError
from sqlalchemy.orm import sessionmaker
from simple_profile.connectors.access import AccessDAO
class RawPyMySQL(object):
def __init__(self, access_dao):
self.acces... |
import json
import socket
try:
import requests
except ImportError:
requests_found = False
else:
requests_found = True
class BigIpCommon(object):
def __init__(self, module):
self._username = module.params.get('user')
self._password = module.params.get('password')
self._hostname... |
from pwnypack.shellcode.base import BaseEnvironment
from pwnypack.shellcode.types import Register
from pwnypack.target import Target
__all__ = ['ARM']
class ARM(BaseEnvironment):
"""
Environment that targets a generic, unrestricted ARM architecture.
"""
target = None #: Target architecture, initia... |
from datetime import timedelta
from django.test import TestCase
from django.utils.timezone import now
from djstripe.models import IdempotencyKey
from djstripe.settings import djstripe_settings
from djstripe.utils import clear_expired_idempotency_keys
class IdempotencyKeyTest(TestCase):
def test_generate_idempot... |
import difflib
import json
import re
from functools import lru_cache
from urllib.parse import urlsplit, urlunparse
import jinja2
from constance import config
from cssselect.parser import SelectorSyntaxError
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.template... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from container.utils.visibility import getLogger
logger = getLogger(__name__)
from container import host_only, conductor_only
CAPABILITIES = dict(
BUILD='building container images',
BUILD_CONDUCTOR='building the Conductor image',
DEPLOY='push... |
import inspect
import operator
import signal
import time
class TimeoutFunctionException(Exception):
"""Exception to raise on a timeout"""
pass
class TimeoutError(Exception):
def __init__(self, message, elapsed=None, *args, **kwargs):
self.elapsed = elapsed
super(TimeoutError, self).__init... |
"""
This class represents the connection to one or more Loco Positioning Anchors
"""
import struct
class LoPoAnchor():
LPP_TYPE_POSITION = 1
LPP_TYPE_REBOOT = 2
LPP_TYPE_MODE = 3
REBOOT_TO_BOOTLOADER = 0
REBOOT_TO_FIRMWARE = 1
MODE_TWR = 1
MODE_TDOA = 2 # TDoA 2
MODE_TDOA3 = 3
... |
import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models import Bill
from opencivicdata.models.people_orgs import Person
EMAIL_FREQUENCIES = (
('N', 'Never'),
('D', 'Daily'),
('W', 'Weekly'),
)
EMAIL_TYPES = (
('H', 'HTML'),
('T', 'Plain Text'... |
import unittest
from datetime import date, datetime, time, timedelta
from django.utils.dateparse import (
parse_date, parse_datetime, parse_duration, parse_time,
)
from django.utils.timezone import get_fixed_timezone
class DateParseTests(unittest.TestCase):
def test_parse_date(self):
# Valid inputs
... |
import sys
class ItemMeanData(object):
def __init__(self):
self.global_sum = 0
self.global_count = 0
self.item_sums = {}
self.item_counts = {}
def train(self, trainfile):
with open(trainfile) as f:
for line in f:
user, item, rating = line.st... |
from django.shortcuts import render
from base.forms import UserEnrollmentForm
from base import models as mdl
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login as django_login
from django.contrib.auth import authenticate
fro... |
# Information
__author__ = "Daniel Roland Henrik Jensen"
__copyright__ = "Copyright (C) 2015 Daniel Jensen"
__license__ = "Apache License 2.0, See the LICENSE file included"
__version__ = "1.0"
# Imports
import sys
import random
import string
from PyQt4 import QtGui, QtCore
# The main window
class main_window(QtGui... |
from ctypes import *
import sys, platform
__LP64__ = (sys.maxint > 2**32)
__i386__ = (platform.machine() == 'i386')
PyObjectEncoding = '{PyObject=@}'
def encoding_for_ctype(vartype):
typecodes = {c_char:'c', c_int:'i', c_short:'s', c_long:'l', c_longlong:'q',
c_ubyte:'C', c_uint:'I', c_ushort:'S... |
"""
Log some text into the terminal.
Copyright (C) 2017 The Pylp Authors.
This file is under the MIT License.
"""
import time
import pylp.cli.colors as colors
import pylp.lib.config as config
# Color separators
# They can be used as follow: "~~color:text"
_color_sep = "~~"
_color_sep2 = ":"
def _make_color_fn(c... |
#!/usr/bin/python
import eyed3
from modules.cleaner import Cleaner
class ID3Helper:
""" eyed3 Helper Class """
audioFile = None
audioFilePath = None
def __init__(self, filepath):
ID3Helper.audioFilePath = filepath
ID3Helper.audioFile = eyed3.load(filepath)
def rename(name):
... |
"""
Forms used for Horizon's auth mechanisms.
"""
import logging
from django import shortcuts
from django.conf import settings
from django.contrib import messages
from django.utils.translation import ugettext as _
from keystoneclient import exceptions as keystone_exceptions
from horizon import api
from horizon impor... |
import inspect
import os.path
import sys
from _pydev_bundle._pydev_tipper_common import do_find
from _pydevd_bundle.pydevd_constants import IS_PY2
if IS_PY2:
from inspect import getargspec as _originalgetargspec
def getargspec(*args, **kwargs):
ret = list(_originalgetargspec(*args, **kwargs)... |
from unittest.mock import patch
import markdown
from django.test import TestCase
from wiki.core.markdown import ArticleMarkdown
from wiki.core.markdown.mdx.codehilite import WikiCodeHiliteExtension
from wiki.core.markdown.mdx.responsivetable import ResponsiveTableExtension
from wiki.models import URLPath
from ..base ... |
"""
Tests for the Kubernetes Job wrapper.
Requires:
- pykube: ``pip install pykube``
- A local minikube custer up and running: http://kubernetes.io/docs/getting-started-guides/minikube/
**WARNING**: For Python versions < 3.5 the kubeconfig file must point to a Kubernetes API
hostname, and NOT to an IP address.
Writ... |
from __future__ import unicode_literals
import frappe, unittest
from frappe.utils import flt
import json
from erpnext.accounts.utils import get_fiscal_year, get_stock_and_account_difference
class TestStockReconciliation(unittest.TestCase):
def test_reco_for_fifo(self):
frappe.defaults.set_global_default("auto_acco... |
"""Morpheme language model model"""
import codecs
import os
import cPickle
import random
from sqlalchemy import Column, Sequence, ForeignKey
from sqlalchemy.types import Integer, Unicode, UnicodeText, DateTime, Boolean, Float
from sqlalchemy.orm import relation
from onlinelinguisticdatabase.model.meta import Base, now... |
# -*- coding: utf-8 -*-
"""
`tvdbsimple` is a wrapper, written in Python, for TheTVDb.com
API v2. By calling the functions available in `tvdbsimple` you can simplify
your code and easily access a vast amount of tv and cast data. To find
out more about TheTVDb API, check out the [official api page](https://api.thet... |
from pyramid.security import (
Allow,
)
from pyramid.view import view_config
from snovault import (
Item,
calculated_property,
collection,
)
from snowflakes.types.base import paths_filtered_by_status
from snovault.attachment import ItemWithAttachment
from snovault.util import Path
from snovault.elastics... |
# -*- coding: utf-8 -*-
import os
import re
import subprocess
from module.plugins.internal.UnRar import UnRar, ArchiveError, CRCError, PasswordError
from module.plugins.internal.utils import fs_join, renice
class SevenZip(UnRar):
__name__ = "SevenZip"
__type__ = "extractor"
__version__ = "0.18"
... |
from django import forms
from django.shortcuts import render
from django.views.generic import CreateView
class ConfirmationMixinException(Exception):
pass
def _merge_dicts(x, y):
return dict(x, **y)
class ConfirmationMixin(object):
"""
Adds a confirmation template to the View.
"""
confirm_... |
"""This code example activates all line items for the given order. To be
activated, line items need to be in the approved state and have at least one
creative associated with them. To approve line items, approve the order to
which they belong by running approve_orders.py. To create LICAs, run
create_licas.py. To determ... |
# -*- coding: utf-8 -*-
""" This module contains logic behind models
Every model inherits from ``Model`` class and it must have an ``objects`` class
variable
"""
class Manager(object):
def create(self, model):
raise NotImplementedError()
def update(self, model):
raise NotImplementedError()
... |
#!/usr/bin/python
import sys, struct, time, fcntl, termios, signal
# struct js_event {
# __u32 time; /* event timestamp in milliseconds */
# __s16 value; /* value */
# __u8 type; /* event type */
# __u8 number; /* axis/button number */
# };
JS_MIN = -32768
JS_MAX = 32... |
from gi.repository import Gio, GLib
from quodlibet import print_d, print_w
from ._base import SessionClient, SessionError
class GnomeSessionClient(SessionClient):
DBUS_NAME = 'org.gnome.SessionManager'
DBUS_OBJECT_PATH = '/org/gnome/SessionManager'
DBUS_MAIN_INTERFACE = 'org.gnome.SessionManager'
DB... |
import json
import os
from copy import deepcopy
from tqdm import tqdm
from parlai.core.agents import create_agent, create_agent_from_model_file
from parlai.core.params import ParlaiParser
import parlai.utils.logging as logging
logging.disable()
SILENCE = '__SILENCE__'
PERSONA_PREFIX = 'your persona: '
ALL_SETTINGS ... |
import requests
from ast import literal_eval
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.views.decorators.csr... |
from django.contrib.auth.models import User
from django.db import models
from caching.base import CachingManager, CachingMixin
from flicks.base import regions
from flicks.base.models import CountryField, LocaleField
# User class extensions
def user_unicode(self):
"""Change user string representation to use the ... |
# -*- coding: utf-8 -*-
import gc
import acf_utils
import sys
import numpy
sys.path.append("../../")
import mir3.data.feature_matrix as feature_matrix
class ModelTesterInput:
def __init__(self, features, filenames):
self.features = features
self.filenames = filenames
class ModelTester:
de... |
# -*- coding: utf-8 -*-
"""Compile source code files from UI files. PyQt5 required."""
__author__ = "Yuan Chang"
__copyright__ = "Copyright (C) 2016-2021"
__license__ = "AGPL"
__email__ = "<EMAIL>"
from os import walk
from os.path import join
from re import sub
from qtpy import PYQT5
if PYQT5:
from PyQt5.uic im... |
#!/usr/bin/env python
import os
from nose.tools import *
from utilities import execution_path
import mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_introspect_symbolizers():
# create a s... |
"""
WebJournal widget - Display weather forecast
"""
import os
import time
import re
import socket
from urllib2 import urlopen
try:
# Try to load feedparser. Remember for later if it was installed
# or not. Note that feedparser is slow to load: if we don't load
# it in a 'global' way, it will be loaded for... |
""" Tests for '--input' and 'input calendar'.
This module contains tests for the '--input' command line option and
for the 'input calendar' configuration file option.
"""
# Copyright 2015, 2016, 2019 Mark Stern
#
# This file is part of Hbcal.
#
# Hbcal is free software: you can redistribute it and/or modify
# it under... |
import os
import sys
import copy
import time
import tarfile
import base64
sys.path.append('../../')
from externals.simple_oss import SimpleOss
from batchcompute import (
Client, JobDescription, TaskDag, TaskDescription, ResourceDescription
)
import config as cfg
oss_clnt = SimpleOss(cfg.OSS_HOST, cfg.ID, cfg.KEY)... |
"""
mediatum - a multimedia content repository
Copyright (C) 2007 Arne Seifert <<EMAIL>>
Copyright (C) 2007 Matthias Kramm <<EMAIL>>
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 vers... |
from oslo_config import cfg
from senlin.api.common import util
from senlin.api.common import wsgi
from senlin.rpc import client as rpc_client
class BuildInfoController(wsgi.Controller):
"""WSGI controller for BuildInfo in Senlin v1 API."""
# Define request scope (must match what is in policy.json)
REQUE... |
__author__ = 'Marc-Andre Gardner'
import datetime
def formatData(name, birth, job, salary):
"""
Rend les parametres d'entree conformes a
certaines specifications.
Retourne aussi un identifiant unique compose
des diverses informations
:param name:
:param birth:
:param job:
:param s... |
from pyfaf.actions import Action
from pyfaf.bugtrackers import bugtrackers
from pyfaf.storage.bugtracker import Bugtracker
from pyfaf.queries import get_bugtracker_by_name
class UpdateBugs(Action):
name = "update-bugs"
def run(self, cmdline, db) -> int:
if cmdline.bugtracker:
tracker = bu... |
import traceback
import logging
from myuw.dao import is_action_disabled
from myuw.dao.instructor_mini_course_card import set_pin_on_teaching_page
from myuw.logger.timer import Timer
from myuw.logger.logresp import log_api_call
from myuw.views.api import ProtectedAPI
from myuw.views.error import handle_exception
from my... |
import logging
from django.core.urlresolvers import reverse
from django.template import defaultfilters as filters
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon i... |
#_*_ coding: UTF-8 _*_
"""
((())) -> YES
()) -> NO
"""
def check(value):
"""This function is problem solving using stack structure."""
cnt = 0
for i in value:
if i == "(":
cnt = cnt+1
else:
if value[cnt-1] == "(":
cnt -= 1
else:
... |
def print_n(x):
print x,
def print_arr(arr):
map(print_n, arr)
print ''
def print_insertion_sort(arr):
for i in range(1, len(arr)):
num_i = arr[i]
k = i
for j in range(i - 1, -1, -1):
if num_i < arr[j]:
print_arr(arr[:j + 1] + arr[j:i] + arr[i + 1:... |
"""Base class for images."""
from ..util import TargetBase
class Image(TargetBase):
"""Base class for images."""
platform_name = None
def __init__(self, platform, config):
"""Set up image.
@param platform: platform object
@param config: image configuration
"""
s... |
"""
Django settings for proxy project.
Generated by 'django-admin startproject' using Django 1.9a1.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
ENV... |
# -*- Mode: Python; tab-width: 4 -*-
# See http://www.xml-rpc.com/
# http://www.pythonware.com/products/xmlrpc/
# Based on "xmlrpcserver.py" by Fredrik Lundh (<EMAIL>)
import http_server
import xmlrpclib
import re
import string
import sys
class xmlrpc_handler:
def __init__(self):
pass
def match (self, re... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... |
import torch
import torch.nn as nn
from collections import OrderedDict
import numpy as np
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_si... |
#!/usr/bin/env python
# a bar plot with errorbars
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
from pylab import *
width=0.28 # the width of the bars
font = {'family' : 'sans-serif',
'variant' : 'normal',
'weight' : 'light',
... |
from solpy import irradiation
import datetime
settings = []
place = (52.01, 4.36)
settings.append({'Name' : 'Surface A',
'Tilt' : 40.0,
'Azimuth' : 180.0,
})
settings.append({'Name' : 'Surface B',
'Tilt' : 90.0,
'Azimuth' : 90.0,
})
#-- Which days
#-- month, day format
epochs = [[3, 1], [6, 21]]
#-- Sampling inte... |
import click
import tensorflow as tf
from luminoth.datasets.exceptions import InvalidDataDirectory
from luminoth.utils.config import parse_override
from .readers import get_reader, READERS
from .writers import ObjectDetectionWriter
@click.command()
@click.option('dataset_reader', '--type', type=click.Choice(READERS.... |
"""
Path sum: two ways
Problem 81
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.
link: https://projecteuler.net/problem=81
Find the minimal path sum, in matrix.txt (right click and "Save Link... |
import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
s... |
import argparse
import functools
import os
import sys
import traceback
from pyasn1.type import univ
from pysnmp.error import PySnmpError
from pysnmp.smi import builder
from pysnmp.smi import compiler
from pysnmp.smi import rfc1902
from pysnmp.smi import view
from snmpsim import error
from snmpsim import utils
from sn... |
import re
from viper.core.config import Config
class TestConfig:
def test_init(self):
instance = Config()
assert isinstance(instance, Config)
assert re.search("viper.conf", instance.config_file)
def test_sample(self):
instance = Config("viper.conf.sample")
assert isin... |
import parole
from parole.colornames import colors
from parole.display import interpolateRGB
import pygame, random
import sim, main
from util import *
from dungeon import makeFloor, Room, TemplateRoom
import dungeon
template = \
"""
## ##### ... ##### #
### ..... ####
# # A .. ... A # ... |
from gi.repository import Gtk, Pango
from pyanaconda.flags import flags
from pyanaconda.i18n import _, C_, CN_
from pyanaconda.packaging import MetadataError
from pyanaconda.threads import threadMgr, AnacondaThread
from pyanaconda import constants
from pyanaconda.ui.communication import hubQ
from pyanaconda.ui.gui.sp... |
from argparse import ArgumentParser
from sys import stdin
def parse_args():
p = ArgumentParser()
p.add_argument('columns', nargs='*', type=int,
help="Specify which columns should be reversed."
"All columns are reversed if not specified")
p.add_argument('-d', '--delimi... |
#!/usr/bin/env python2.7
"""
This script takes the name of another python script (let's say some_script.py)
and launches N parallel instances of some_script.py on the short queue as an
array job. Each instance of some_script.py will get passed
--chrom, --start-pos, and --end-pos args which will define the genomic
reg... |
#!/usr/bin/python
import os, sys
import zmq
import RPi.GPIO as GPIO
import time
import math
import logging
import sched
import scipy.optimize
import subprocess
from lapse_util import Info
import lapse_util as util
# Prerequisities:
# remi (download and install with python setup.py)
# zeromq (pip install zmq)
# scip... |
"""
PXE Driver and supporting meta-classes.
"""
from oslo.utils import importutils
from ironic.common import exception
from ironic.common.i18n import _
from ironic.drivers import base
from ironic.drivers.modules import iboot
from ironic.drivers.modules.ilo import deploy as ilo_deploy
from ironic.drivers.modules.ilo i... |
"""
The MatchMaker classes should except a Topic or Fanout exchange key and
return keys for direct exchanges, per (approximate) AMQP parlance.
"""
import contextlib
import logging
import eventlet
from oslo.config import cfg
# FIXME(markmc): remove this
_ = lambda s: s
matchmaker_opts = [
cfg.IntOpt('matchmaker_... |
import io
import csv
import errno
import os
import stat
import re
import shutil
import logging
import traceback
from datetime import datetime
from sis_provisioner.util.log import log_exception
FILEMODE = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP |
stat.S_IROTH)
# ugo+x
DIRMODE = FILEMODE ... |
from __future__ import absolute_import
import ujson
from .kafka_base_monitor import KafkaBaseMonitor
import yaml
from kazoo.client import KazooClient
from kazoo.exceptions import ZookeeperError
class ZookeeperMonitor(KafkaBaseMonitor):
regex = "zk:*:*:*"
def setup(self, settings):
'''
Setup ... |
import logging
import subprocess
import verboselogs
from openpyn import __basefilepath__, api
from openpyn.converter import T_CLIENT, Converter
verboselogs.install()
logger = logging.getLogger(__package__)
def run(server, c_code, client, rgw=None, comp=None, adns=None, tcp=False, test=False, debug=False):
with... |
import bpy
def swimregion(modifier, layout, context):
split = layout.split()
col = split.column()
col.label("Detector Region:")
col.prop(modifier, "region", text="")
region_bo = modifier.region
col = split.column()
col.enabled = region_bo is not None
bounds_src = region_bo if region_bo... |
from cloudbaseinit.openstack.common import cfg
from cloudbaseinit.openstack.common import log as logging
from cloudbaseinit.osutils import factory as osutils_factory
from cloudbaseinit.plugins import base
from cloudbaseinit.plugins import constants
opts = [
cfg.StrOpt('username', default='Admin', help='User to be ... |
#!/usr/bin/env python
##
## html2txt.py - strip printable texts from html files.
##
## by Yusuke Shinyama, May 2003
##
import sys, sgmllib
class Parser(sgmllib.SGMLParser):
def __init__(self):
sgmllib.SGMLParser.__init__(self)
self.t = 0
self.ok = 1
return
def handle_data(self, x):
if not se... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx... |
from flask import Blueprint
from flask import render_template, redirect, url_for, jsonify, request
from nltk.corpus import gutenberg
from nltk.corpus import nps_chat
from nltk.corpus import brown
from . import controllers
helpers = Blueprint('helpers', __name__)
@helpers.route('/')
def verify_api_01():
response... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import os
import psycopg2
import time
import config
import argparse
def download_osm():
import urllib
urllib.urlretrieve ('''http://overpass.osm.rambler.ru/cgi/interpreter?data=%5Bout%3Axml%5D%5Btimeout%3A25%5D%3B%28relation%5B%22route%22%3D%22trolleybus%22%5D%2859%2E80754... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.